/*
 Copyright (c) 2010 Konstantin Denerz
 Licensed under the MIT license (MIT-LICENSE.txt):
 http://www.opensource.org/licenses/mit-license.php
 */
var tryLog = function(context){
    if (console && console.log) {
        console.log(context);
    }
}


function run(tests){

    /**
     * @param {String} test
     */
    var generateImport = function(test){
        return '<script src="tests/' + test + '.js" type="text/javascript"></script>';
    };
    
    var jsImport = null;
    var currentTest = null;
    
    for (var index in tests) {
        currentTest = tests[index];
        jsImport = generateImport(currentTest);
        var currentTestFile = "tests/" + currentTest + ".js"
        module('<a href="' + currentTestFile + '" title="' + currentTestFile + '" >' + currentTest + '</a>');
        $("head").append(jsImport);
        tryLog(["JavaScript import", jsImport]);
    }
}

var jsonToString = function(json){
    var result = "{";
    for (var property in json) {
        result += property + "=" + json[property] + ",";
    }
    if (result[result.length - 1] == ",") {
        result = result.substr(0, result.length - 1);
    }
    result += "}";
    return result;
};

function tryIt(method, message, withException){

    var hasException = invokeWithErrorHandling(method);
    
    if (hasException) {
        if (hasException && withException && hasException.type && withException.type && hasException.type == withException.type) {
            ok(true, [message, method]);
        }
        else {
            var exception = $.isPlainObject(hasException) ? jsonToString(hasException) : hasException;
            equals("exception: " + exception, "result", [message, method]);
        }
    }
    else {
        if (withException) {
            equals("without exception", "exception", [message, method]);
        }
        else {
            ok(true, [message, method]);
        }
    }
    
    return hasException;
}

function invokeWithErrorHandling(method){
    try {
        method();
    } 
    catch (exception) {
        return exception;
    }
    return;
}

